﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using Ent;
using BLL;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
namespace Thi
{
    public partial class frmThi : DevComponents.DotNetBar.OfficeForm
    {
        List<TextBox> listText = new List<TextBox>();
        ChiTietDeThiBLL bll;
        List<CauHoiThi> dsTron;
        List<TraLoiThi> dsDapAnDaTron;
        List<int> DapAnChecked;
        int VitriCau = 1;
        string Made = "";
        string mssv = "";
        string hoten = "";
        string mamonhoc = "";
        int time = 0;
        int gio = 0;
        int phut = 0;
        int giay = 0;
        public frmThi(string Made, string mssv, string hoten, List<CauHoiThi> danhsachcauhoi, List<TraLoiThi> danhsachdapan, string mamonhoc)
        {
            this.mamonhoc = mamonhoc;
            this.Made = Made;
            this.mssv = mssv;
            this.hoten = hoten;
            dsTron = new List<CauHoiThi>();
            dsTron = danhsachcauhoi;
            dsDapAnDaTron = new List<TraLoiThi>();
            dsDapAnDaTron = danhsachdapan;
            InitializeComponent();
        }

        private void frmThi_Load(object sender, EventArgs e)
        {
            ProcessModule objCurrentModule = Process.GetCurrentProcess().MainModule;
            objKeyboardProcess = new LowLevelKeyboardProc(captureKey);
            ptrHook = SetWindowsHookEx(13, objKeyboardProcess, GetModuleHandle(objCurrentModule.ModuleName), 0);
            this.WindowState = FormWindowState.Normal;
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            this.Bounds = Screen.PrimaryScreen.Bounds;
            lblHoTen.Text = hoten;
            lblMSSV.Text = mssv;
            MonHocBLL mhbll = new MonHocBLL();
            MonHocTbl mh = mhbll.LayMonHoc_TheoMaDethi(Made);
            lblMonHoc.Text = mh.TenMonHoc;
            DeThiBLL dtbll = new DeThiBLL();
            DeThiTbl dthi = dtbll.ThongTinDeTHi_Madethi(Made);
            time = dthi.THOIGIAN;
            lblTime.Text = dthi.THOIGIAN.ToString() + " phút";
            DapAnChecked = new List<int>();
            bll = new ChiTietDeThiBLL();
            BusinessLogicLayer dt = new BusinessLogicLayer();
            for (int i = 0; i < dsTron.Count; i++)
            {
                DapAnChecked.Add(0);
                AddButton(i);
            }
            HienThiCauHoi();
            HienThiDapAn();
            HienThi_LabelVitriCau();
            lblCauDaLam.Text = DemSocauTraloi().ToString();
            lblCauChuaLam.Text = DemsocauChuatraLoi().ToString();
            lblCau.Text = "Câu " + VitriCau.ToString();
            gio = time / 60;
            phut = time - 60 * gio;
            giay = 0;
            lblTimeout.Text = "<b><font size='+6'><font color='#B02B2C'>" + gio + ":" + phut + ":" + giay + "</font></font></b>";
            timer1.Enabled = true;
            timer1.Start();
            timer1.Interval = 1000;
            progressBar1.Maximum = time * 60;
            timer1.Tick += timer1_Tick;
            //<b><font size="+6"><font color="#B02B2C">00:00:00</font></font></b>

        }
        public void CloseForm()
        {
            foreach (Form frm in this.MdiChildren)
            {
                    frm.Close();
            }
        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (gio > 0)
                if (phut > 0)
                    if (giay > 0)
                        giay--;
                    else
                    {
                        giay = 59;
                        phut--;
                    }
                else
                    if (giay > 0)
                        giay--;
                    else
                    {
                        phut = 59;
                        gio--;
                    }
            else
                if (gio == 0)
                    if (phut > 0)
                        if (giay > 0)
                            giay--;
                        else
                        {
                            giay = 59;
                            phut--;
                        }
                    else
                        giay--;
            lblTimeout.Text = "<b><font size='+6'><font color='#B02B2C'>" + ((gio < 10) ? "0" + gio.ToString() : gio.ToString()) + ":" + ((phut < 10) ? "0" + phut.ToString() : phut.ToString()) + ":" + ((giay < 10) ? "0" + giay.ToString() : giay.ToString()) + "</font></font></b>";
            progressBar1.Value++;
            progressBar1.Text = (progressBar1.Value * 100 / (time * 60)).ToString() + " %";
            if (gio == 0 && phut == 0 && giay == 0)
            {
                frmKetQua frm = new frmKetQua(Made, mssv, dsTron, dsDapAnDaTron);
                CloseForm();
                frm.Show();
                this.Hide();
                timer1.Stop();
                if (frm1 != null)
                    frm1.Close();
            }
        }
        private void AddButton(int index)
        {
            Button button1 = new Button();
            int x = index + 1;
            button1.Text = "Câu " + x;
            button1.Name = "btn" + (x).ToString();
            button1.BackColor = Color.Empty;
            button1.ForeColor = Color.Black;
            button1.Size = new System.Drawing.Size(120, 30);
            button1.Click += new System.EventHandler(OnClickButton);
            button1.Leave += new EventHandler(LeaveButton);
            flPnlCauhoi.Controls.Add(button1);
        }
        private void LeaveButton(object sender, EventArgs e)
        {
            Button a = (sender as Button);
            a.BackColor = Color.Empty;
            a.ForeColor = Color.Black;
        }
        void OnClickButton(object sender, System.EventArgs e)
        {
            VitriCau = int.Parse((sender as ButtonBase).Name.Substring(3));
            HienThiCauHoi();
            HienThiDapAn();
            (sender as ButtonBase).BackColor = Color.Red;
            (sender as ButtonBase).ForeColor = Color.White;

            if (VitriCau == dsTron.Count)
            {
                btnCauSau.Enabled = false;

            }
            else
            {
                btnCauSau.Enabled = true;
            }
            if (VitriCau == 1)
            {
                btnCauTruoc.Enabled = false;

            }
            else
            {
                btnCauTruoc.Enabled = true;
            }
            HienThi_LabelVitriCau();
        }
        public void HienThi_LabelVitriCau()
        {
            lblCau.Text = "Câu " + VitriCau;
            string s = "Câu ";
            int x = dsTron.Count;
            lblVitriCau.Text = s + VitriCau.ToString() + @" \ " + x.ToString();
        }
        public string MaCauHoi_btn(int index)
        {
            return dsTron[index].MaCauHoi;
        }
        public List<TraLoiThi> Dsdapan_Macauhoi(string Macauhoi)
        {
            List<TraLoiThi> ds = new List<TraLoiThi>();
            foreach (TraLoiThi da in dsDapAnDaTron)
            {
                if (da.MaCauHoi == Macauhoi)
                    ds.Add(da);

            }
            return ds;
        }
        public void HienThiDapAn()
        {
            List<TraLoiThi> ds = new List<TraLoiThi>();
            ds = Dsdapan_Macauhoi(MaCauHoi_btn(VitriCau - 1));
            int sodapan = ds.Count;
            int sodapandung = dsTron[VitriCau - 1].SoDapAnDung;
            if (sodapandung == 1)
            {
                createDapAn_Radiobutton(ds);
            }
            else
            {
                createDapAn_Checkbox(ds);
            }
        }
        public void createDapAn_Radiobutton(List<TraLoiThi> dsdapan)
        {
            grouppnl.Controls.Clear();
            int line = 0;
            for (int x = 1; x <= dsdapan.Count; x++)
            {
                RadioButton ra = new RadioButton();
                ra.Name = "rdb" + x.ToString();
                ra.Text = null;
                ra.Size = new System.Drawing.Size(30, 30);
                ra.RightToLeft = System.Windows.Forms.RightToLeft.Yes;
                ra.CheckedChanged += ra_CheckedChanged;
                ra.Location = new Point(54, 12 + line);
                ra.TabIndex = 1;

                //----------------
                TextBox b = new TextBox();
                b.Name = "txt" + x.ToString();
                b.BorderStyle = BorderStyle.None;
                b.Multiline = true;
                b.Size = new Size(751, 55);
                b.ReadOnly = true;
                b.ScrollBars = ScrollBars.Vertical;
                b.Location = new Point(128, 11 + line);
                b.Text = dsdapan[x - 1].NoiDung;
                b.TabIndex = 111;
                b.AcceptsTab = false;

                if (dsdapan[x - 1].LoaiDA == 1)
                {
                    ra.Checked = true;
                }
                else
                {
                    ra.Checked = false;
                }
                //-------------------
                PictureBox pic = new PictureBox();
                pic.Name = "pic" + x.ToString();
                pic.Width = 299;
                pic.Height = 68;
                pic.Location = new Point(895, 2 + line);
                pic.SizeMode = PictureBoxSizeMode.StretchImage;
                pic.BorderStyle = BorderStyle.FixedSingle;
                grouppnl.Controls.Add(ra);
                grouppnl.Controls.Add(b);
                grouppnl.Controls.Add(pic);
                line += 70;
                if (dsdapan[x - 1].HinhAnh != "" && dsdapan[x - 1].HinhAnh != null)
                {
                    pic.ImageLocation = dsdapan[x - 1].HinhAnh;
                    pic.Visible = true;
                }
                else
                {
                    pic.ImageLocation = "";
                    pic.Visible = false;
                }
            }
        }
        private void ra_CheckedChanged(object sender, EventArgs e)
        {
            RadioButton ra = sender as RadioButton;
            if (ra.Checked)
            {
                int s = int.Parse(ra.Name.Substring(3).ToString());
                ChonDapAn(1, MaCauHoi_btn(VitriCau - 1), s - 1, 1);

            }
            lblCauChuaLam.Text = DemsocauChuatraLoi().ToString();
            lblCauDaLam.Text = DemSocauTraloi().ToString();
        }
        public int DemSocauTraloi()
        {
            int x = 0;
            int tam = 0;
            foreach (CauHoiThi ch in dsTron)
            {
                int temp = 0;
                foreach (TraLoiThi tl in dsDapAnDaTron)
                {
                    if (tl.MaCauHoi == ch.MaCauHoi && tl.LoaiDA == 1)
                    {
                        temp = 1;
                    }
                }
                if (temp == 1)
                {

                    x++;
                }
                DapAnChecked[tam] = temp;
                tam++;
            }
            return x;
        }
        public int DemsocauChuatraLoi()
        {
            return (dsTron.Count - DemSocauTraloi());
        }
        public void ChonDapAn(int HinhThuc, string MaCauHoi, int index, int LoaiDapan)
        {

            int tam = 0;
            if (HinhThuc == 0)
            {
                //checkbox
                foreach (TraLoiThi da in dsDapAnDaTron)
                {
                    if (da.MaCauHoi == MaCauHoi)
                    {
                        if (tam == index)
                        {
                            da.LoaiDA = LoaiDapan;
                            break;
                        }
                        tam++;
                    }
                }
            }
            else
            {
                //radio
                foreach (TraLoiThi da in dsDapAnDaTron)
                {
                    if (da.MaCauHoi == MaCauHoi)
                    {
                        if (tam == index)
                        {
                            da.LoaiDA = 1;
                            break;
                        }
                        else
                        {
                            da.LoaiDA = 0;
                        }
                        tam++;
                    }
                }
            }

        }
        private void chk_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox chk = sender as CheckBox;
            int k = 0;
            if (chk.Checked) k = 1;
            else k = 0;
            int s = int.Parse(chk.Name.Substring(3).ToString());
            ChonDapAn(0, MaCauHoi_btn(VitriCau - 1), s - 1, k);
            lblCauChuaLam.Text = DemsocauChuatraLoi().ToString();
            lblCauDaLam.Text = DemSocauTraloi().ToString();
        }
        public void createDapAn_Checkbox(List<TraLoiThi> dsdapan)
        {
            grouppnl.Controls.Clear();
            int line = 0;
            for (int x = 1; x <= dsdapan.Count; x++)
            {
                CheckBox chk = new CheckBox();
                chk.Name = "chk" + x.ToString();
                chk.Size = new System.Drawing.Size(30, 30);
                chk.RightToLeft = System.Windows.Forms.RightToLeft.Yes;
                chk.CheckedChanged += chk_CheckedChanged;
                chk.Location = new Point(54, 12 + line);
                chk.TabIndex = 0;
                TextBox b = new TextBox();
                b.Name = "txt" + x.ToString();
                b.Multiline = true;
                b.Size = new Size(751, 55);
                b.ReadOnly = true;
                b.ScrollBars = ScrollBars.Vertical;
                b.Location = new Point(128, 11 + line);
                b.Text = dsdapan[x - 1].NoiDung;
                b.TabIndex = 111;
                b.BorderStyle = BorderStyle.None;
                if (dsdapan[x - 1].LoaiDA == 0)
                {
                    chk.Checked = false;
                }
                else
                {
                    chk.Checked = true;
                }

                PictureBox pic = new PictureBox();
                pic.Name = "pic" + x.ToString();
                pic.Width = 299;
                pic.Height = 68;
                pic.Location = new Point(895, 2 + line);
                pic.BorderStyle = BorderStyle.FixedSingle;
                grouppnl.Controls.Add(chk);
                grouppnl.Controls.Add(b);
                grouppnl.Controls.Add(pic);
                line += 70;
                if (dsdapan[x - 1].HinhAnh != "" && dsdapan[x - 1].HinhAnh != null)
                {
                    pic.ImageLocation = dsdapan[x - 1].HinhAnh;
                    pic.Visible = true;
                }
                else
                {
                    pic.ImageLocation = "";
                    pic.Visible = false;
                }
                pic.SizeMode = PictureBoxSizeMode.StretchImage;
            }
        }
        private void txtNoiDung_ContentsResized(object sender, ContentsResizedEventArgs e)
        {
            txtNoiDung.Height = e.NewRectangle.Height;
        }
        private void txtNoiDung_TextChanged(object sender, EventArgs e)
        {
            Graphics gs = Graphics.FromHwnd(this.Handle);
            Font f = this.txtNoiDung.Font;
            if (this.txtNoiDung.Text != "")
            {
                SizeF sf = gs.MeasureString(this.txtNoiDung.Text, f);
                int hi = (int)(sf.Width / (this.txtNoiDung.Width - SystemInformation.VerticalScrollBarWidth)) + 1;
                MatchCollection mat = Regex.Matches(txtNoiDung.Text, @"\n");
                this.txtNoiDung.Height = Convert.ToInt16(hi * f.Height) + 10 + mat.Count*26;
            }
        }
        public void HienThiCauHoi()
        {
            foreach (CauHoiThi ch in dsTron)
            {
                if (ch.MaCauHoi == MaCauHoi_btn(VitriCau - 1))
                {
                    txtNoiDung.Text = ch.NoiDung;
                    txtNoiDung.TextChanged += txtNoiDung_TextChanged;
                    txtNoiDung.ContentsResized += txtNoiDung_ContentsResized;
                    if (ch.HinhAnh != null && ch.HinhAnh != "")
                    {
                        picNoiDung.ImageLocation = ch.HinhAnh;
                        picNoiDung.Visible = true;
                    }
                    else
                    {
                        picNoiDung.ImageLocation = "";
                        picNoiDung.Visible = false;
                    }
                    if (ch.Flag == 0)
                        chkFlag.Checked = false;
                    else
                        chkFlag.Checked = true;
                    picNoiDung.SizeMode = PictureBoxSizeMode.StretchImage;
                    picNoiDung.Height = panel2.Height;
                }
            }
        }
        [StructLayout(LayoutKind.Sequential)]
        private struct KBDLLHOOKSTRUCT
        {
            public Keys key;
            public int scanCode;
            public int flags;
            public int time;
            public IntPtr extra;
        }
        //System level functions to be used for hook and unhook keyboard input  
        private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr SetWindowsHookEx(int id, LowLevelKeyboardProc callback, IntPtr hMod, uint dwThreadId);
        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern bool UnhookWindowsHookEx(IntPtr hook);
        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr CallNextHookEx(IntPtr hook, int nCode, IntPtr wp, IntPtr lp);
        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr GetModuleHandle(string name);
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        private static extern short GetAsyncKeyState(Keys key);
        //Declaring Global objects     
        private IntPtr ptrHook;
        private LowLevelKeyboardProc objKeyboardProcess;

        private IntPtr captureKey(int nCode, IntPtr wp, IntPtr lp)
        {
            if (nCode >= 0)
            {
                KBDLLHOOKSTRUCT objKeyInfo = (KBDLLHOOKSTRUCT)Marshal.PtrToStructure(lp, typeof(KBDLLHOOKSTRUCT));

                // Disabling Windows keys 

                if (objKeyInfo.key == Keys.RWin || objKeyInfo.key == Keys.LWin || objKeyInfo.key == Keys.Tab && HasAltModifier(objKeyInfo.flags) || objKeyInfo.key == Keys.Escape && (ModifierKeys & Keys.Control) == Keys.Control || (ModifierKeys & Keys.Alt) == Keys.Alt && (ModifierKeys & Keys.Control) == Keys.Control && (ModifierKeys & Keys.Delete) == Keys.Delete || (ModifierKeys & Keys.Alt) == Keys.Alt && objKeyInfo.key == Keys.F4)
                {
                    return (IntPtr)1; // if 0 is returned then All the above keys will be enabled
                }
                if ((ModifierKeys & Keys.Alt) == Keys.Alt && (ModifierKeys & Keys.Control) == Keys.Control && (ModifierKeys & Keys.Delete) == Keys.Delete)
                {
                    return (IntPtr)1;
                }

            }
            return CallNextHookEx(ptrHook, nCode, wp, lp);
        }
        bool HasAltModifier(int flags)
        {
            return (flags & 0x20) == 0x20;
        }

        frmFlag frm1;
        private void btnChonNhanh_Click(object sender, EventArgs e)
        {
            //Goi form con day//
            //frmFlag frm = new frmFlag(dsTron, DapAnChecked,progressBar1.Value,progressBar1.Maximum);
            frm1 = new frmFlag(dsTron, DapAnChecked);
            if (frm1.ShowDialog() == DialogResult.OK)
            {

                VitriCau = frm1.ChkChecked;
                HienThi_LabelVitriCau();
                HienThiCauHoi();
                HienThiDapAn();
            }
        }

        private void chkFlag_CheckedChanged(object sender, EventArgs e)
        {
            int x = 0;
            if (chkFlag.Checked == true)
            {
                x = 1;
            }
            foreach (CauHoiThi ch in dsTron)
            {
                if (ch.MaCauHoi == MaCauHoi_btn(VitriCau - 1))
                {
                    ch.Flag = x;
                }
            }
        }

        private void btnNopBai_Click(object sender, EventArgs e)
        {
            if (progressBar1.Value < time * 2 * 60 / 3)
            {
                MessageBox.Show("Hết 2/3 thời gian thì bạn mới được nộp bài!");
                return;
            }
            else
            {
                if (MessageBox.Show("Bạn có chắc nộp bài chứ?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                {
                    frmKetQua frm = new frmKetQua(Made, mssv, dsTron, dsDapAnDaTron);
                    this.Hide();
                    frm.Show();
                }
                else
                {
                    return;
                }
            }
        }

        private void btnCauSau_Click(object sender, EventArgs e)
        {
            if (VitriCau == dsTron.Count)
            {
                return;
            }
            if (btnCauTruoc.Enabled == false)
            {

                btnCauTruoc.Enabled = true;
            }
            if (VitriCau == dsTron.Count - 1)
            {
                btnCauSau.Enabled = false;

            }
            VitriCau++;
            HienThiCauHoi();
            HienThiDapAn();

            HienThi_LabelVitriCau();
        }

        private void btnCauTruoc_Click(object sender, EventArgs e)
        {
            if (VitriCau == 1)
            {
                return;
            }
            if (btnCauSau.Enabled == false)
            {

                btnCauSau.Enabled = true;
            }
            if (VitriCau == 2)
            {
                btnCauTruoc.Enabled = false;

            }
            VitriCau--;
            HienThiCauHoi();
            HienThiDapAn();
            Button a = new Button();
            a.Name = "btn" + VitriCau;
            OnClickButton(a, e);
            HienThi_LabelVitriCau();
        }
    }
}